package com.azkj.album.view.fragment.gallery;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.azkj.album.R;
import com.azkj.album.adapter.CategoryAdapter;
import com.azkj.album.adapter.GalleryAdapter;
import com.azkj.album.dto.CategoryBean;
import com.azkj.album.dto.GalleryBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.utils.DownLoadApkUtils;
import com.azkj.album.utils.ImageLoader;
import com.azkj.album.utils.SoftKeyBoardListener;
import com.azkj.album.utils.Utils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.base.BaseFragment;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.azkj.album.view.widgets.dialog.DialogHelper;
import com.azkj.album.view.widgets.dialog.FeedDialog;
import com.azkj.album.view.widgets.dialog.ShareBottomDialog;
import com.azkj.album.view.widgets.staggedrv.GridItemDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class GalleryChildFragment extends BaseFragment {

    public static final String GALLERY_SYS = "gallery_sys";
    public static final String GALLERY_MINE = "gallery_mine";
    public static final String GALLERY_COLLECT = "gallery_collect";

    private String GALLERY_TYPE = GALLERY_SYS;

    @BindView(R.id.top)
    LinearLayout top;
    @BindView(R.id.top_search)
    EditText top_search;
    @BindView(R.id.action_search)
    TextView action_search;
    @BindView(R.id.top_nums)
    LinearLayout top_nums;
    @BindView(R.id.nums_up)
    ImageView nums_up;
    @BindView(R.id.nums_down)
    ImageView nums_down;
    @BindView(R.id.top_time)
    LinearLayout top_time;
    @BindView(R.id.time_up)
    ImageView time_up;
    @BindView(R.id.time_down)
    ImageView time_down;
    @BindView(R.id.category_list)
    RecyclerView category_list;

    @BindView(R.id.conten_refresh)
    SmartRefreshLayout conten_refresh;
    @BindView(R.id.content_list)
    RecyclerView content_list;
    @BindView(R.id.control_sys)
    TextView control_sys;
    @BindView(R.id.control_mine)
    ImageView control_mine;


    private GalleryAdapter mAdapter;
    private CategoryAdapter categoryAdapter;

    private String category_id = "";
    private String keyword = "";
    private int page = 1;
    private String sort_field = "";
    private String sort_order = "";

    private static OnGallerySelListener mListener;


    public static GalleryChildFragment newInstance(String type, OnGallerySelListener listener) {
        GalleryChildFragment galleryChildFragment = new GalleryChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        galleryChildFragment.setArguments(bundle);
        mListener = listener;
        return galleryChildFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_gallery_child;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        backgroundLayoutListener();
    }

    @Override
    public void onVisible() {
        super.onVisible();
        if (GALLERY_TYPE.equals(GALLERY_COLLECT)) {
            conten_refresh.autoRefresh();
        }
    }

    protected void backgroundLayoutListener() {
        SoftKeyBoardListener softKeyBoardListener = SoftKeyBoardListener.newInstance(getActivity());
        softKeyBoardListener.setOnSoftKeyBoardChangeListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                top_search.clearFocus();
                action_search.setVisibility(View.GONE);
                top_nums.setVisibility(View.VISIBLE);
                top_time.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initData() {
        Bundle bundle = getArguments();
        GALLERY_TYPE = bundle.getString("type");
        Log.e(TAG, "type is " + GALLERY_TYPE);
        top_search.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED ||
                    actionId == EditorInfo.IME_ACTION_SEARCH ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
            ) {
                keyword = top_search.getText().toString();
                loadContent();
                top_search.clearFocus();
                Utils.hideKeyboard(v);
                return true;
            }
            return false;
        });
        top_search.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
//                action_search.setVisibility(View.VISIBLE);
                top_nums.setVisibility(View.GONE);
                top_time.setVisibility(View.GONE);
            } else {
                action_search.setVisibility(View.GONE);
                top_nums.setVisibility(View.VISIBLE);
                top_time.setVisibility(View.VISIBLE);
            }
        });

        top_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyword = top_search.getText().toString();
                loadContent();
            }
        });

        category_list.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false));
        content_list.setLayoutManager(new LinearLayoutManager(getActivity()));

        conten_refresh.setRefreshHeader(new ClassicsHeader(getActivity()));
        conten_refresh.setRefreshFooter(new ClassicsFooter(getActivity()));
        conten_refresh.setEnableLoadMore(GALLERY_TYPE.equals(GALLERY_SYS));

        conten_refresh.setOnRefreshListener(refreshLayout -> {
            page = 1;
            loadContent();
        });

        conten_refresh.setOnLoadMoreListener(refreshLayout -> {
            page++;
            loadContent();
        });

        mAdapter = new GalleryAdapter(R.layout.item_gallery);
        mAdapter.bindToRecyclerView(content_list);
        mAdapter.setEmptyView(R.layout.list_empty);
        mAdapter.setType(GALLERY_TYPE);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            GalleryBean item = mAdapter.getData().get(position);
            switch (view.getId()) {
                case R.id.iv_download:
                    downloadUrl(item.getId(), item.getImage(), item.getName(), position);
                    break;
                case R.id.iv_collect:
                    collect(item, position);
                    break;
                case R.id.iv_share:
                    showBottomDialog(item, false,position);
                    break;
                case R.id.iv_image:
//                    if (mListener != null) {
//                        mListener.onSel(item);
//                    }
                    new XPopup.Builder(getActivity())
                            .asImageViewer((ImageView) view.findViewById(R.id.iv_image), item.getImage(),
                                    false, -1, -1, -1,
                                    false, new ImageLoader(new Function1<Object, Unit>() {
                                        @Override
                                        public Unit invoke(Object o) {
                                            showBottomDialog(item, true,-1);
                                            return null;
                                        }
                                    }))
                            .show();
                    break;

                case R.id.iv_del:
                    new CommonDialog.Builder(getActivity()).setTitle("提示")
                            .setDesc("确认删除该贴图").setOnClickListener((dialog, confirm) -> {
                                if (confirm) {
                                    delMine(item, position);
                                }
                                dialog.dismiss();
                            }).show();

                    break;
            }
        });

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mListener != null) {
                GalleryBean item = mAdapter.getData().get(position);
                mListener.onSel(item);
            }
        });

        content_list.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        content_list.addItemDecoration(new GridItemDecoration(getContext(), 10));
        content_list.setAdapter(mAdapter);

        if (GALLERY_TYPE == GALLERY_MINE) {
            control_mine.setVisibility(View.VISIBLE);
            top.setVisibility(View.GONE);
            category_list.setVisibility(View.GONE);
        } else {
            if (GALLERY_TYPE == GALLERY_SYS) {
                control_sys.setVisibility(View.VISIBLE);
            }
            categoryAdapter = new CategoryAdapter(R.layout.item_category);
            categoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    categoryAdapter.setCurPosition(position);
                    category_id = categoryAdapter.getData().get(position).getId();
                    if ("-1" == category_id) {
                        category_id = "";
                    }
                    page = 1;
                    loadContent();
                }
            });
            category_list.setVisibility(View.VISIBLE);
            category_list.setAdapter(categoryAdapter);
            NetworkMaster.getInstance().getCommonService().gallerySysCategory(new ServiceCallback<BaseResp<List<CategoryBean>>>() {

                @Override
                public void onSuccess(BaseResp resp) {
                    List<CategoryBean> data = (List<CategoryBean>) resp.getData();
                    if (null == data) {
                        data = new ArrayList<>();
                    }
                    CategoryBean all = new CategoryBean();
                    all.setId("-1");
                    all.setName("全部");
                    data.add(0, all);
                    categoryAdapter.setNewData(data);
                }

                @Override
                public void onError(ApiException apiException) {
                    ToastUtils.showCenterToast(apiException.errorInfo.error);
                }
            });
        }

        DialogHelper.showFailDialog("加载中", 0);
        loadContent();
    }

    private void showBottomDialog(GalleryBean item, boolean isShowDownload,int position) {
        new ShareBottomDialog.Builder(getActivity())
                .setShowDownLoad(isShowDownload).setCallBack(
                        new ShareBottomDialog.Builder.ItemClickListener() {
                            @Override
                            public void onFriendClick() {
                                ((BaseActivity) getActivity()).shareImageToWx(item.getId(),item.getImage(), true,position);
                            }

                            @Override
                            public void onZoneClick() {
                                ((BaseActivity) getActivity()).shareImageToWx(item.getId(),item.getImage(), false,position);

                            }

                            @Override
                            public void onDyClick() {
                                ((BaseActivity) getActivity()).shareImgToDy(item.getId(),item.getImage(), item.getName(),position);

                            }

                            @Override
                            public void onDownload() {
                                downloadUrl(item.getId(),item.getImage(), item.getName(),position);
                            }
                        }
                ).show();
    }

    @OnClick({R.id.top_search, R.id.action_search, R.id.control_mine, R.id.control_sys, R.id.top_time, R.id.top_nums})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_search:
//                action_search.setVisibility(View.VISIBLE);
                top_nums.setVisibility(View.GONE);
                top_time.setVisibility(View.GONE);
                break;
            case R.id.action_search:
                keyword = top_search.getText().toString();
                loadContent();
                top_search.clearFocus();
                action_search.setVisibility(View.GONE);
                top_nums.setVisibility(View.VISIBLE);
                top_time.setVisibility(View.VISIBLE);
                break;
            case R.id.control_mine:
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_FRAGMENT_UPLOAD_MAP_CLICK));
                break;
            case R.id.control_sys:
                new FeedDialog.Builder(getActivity()).show();
                break;
            case R.id.top_time:
//                top_time.setBackgroundResource(R.drawable.shape_ebf3ff_corner_30);
//                top_nums.setBackgroundResource(R.drawable.bg_stroke_e2e2e2);
                sort_field = "createtime";
                if ("asc".equals(sort_order)) {
                    sort_order = "desc";
                    time_down.setVisibility(View.VISIBLE);
                    time_up.setVisibility(View.INVISIBLE);
                } else {
                    sort_order = "asc";
                    time_down.setVisibility(View.INVISIBLE);
                    time_up.setVisibility(View.VISIBLE);
                }
//                nums_up.setVisibility(View.VISIBLE);
//                nums_down.setVisibility(View.VISIBLE);
                content_list.smoothScrollToPosition(0);
                page = 1;
                loadContent();
                break;
            case R.id.top_nums:
//                top_time.setBackgroundResource(R.drawable.bg_stroke_e2e2e2);
//                top_nums.setBackgroundResource(R.drawable.shape_ebf3ff_corner_30);
                sort_field = "use_count";
                if ("asc".equals(sort_order)) {
                    sort_order = "desc";
                    nums_down.setVisibility(View.VISIBLE);
                    nums_up.setVisibility(View.INVISIBLE);
                } else {
                    sort_order = "asc";
                    nums_down.setVisibility(View.INVISIBLE);
                    nums_up.setVisibility(View.VISIBLE);
                }
//                time_up.setVisibility(View.VISIBLE);
//                time_down.setVisibility(View.VISIBLE);
                content_list.smoothScrollToPosition(0);
                page = 1;
                loadContent();
                break;
        }
    }

    private void loadContent() {
        if (Objects.equals(GALLERY_TYPE, GALLERY_SYS)) {
            NetworkMaster.getInstance().getCommonService().gallerySysList(category_id, keyword, String.valueOf(page)
                    , sort_field, sort_order, new ServiceCallback<BaseResp<List<GalleryBean>>>() {

                        @Override
                        public void onSuccess(BaseResp<List<GalleryBean>> resp) {
                            DialogHelper.hideDialog();
                            if (page == 1) {
                                mAdapter.setNewData(resp.getData());
                            } else {
                                if (null == resp.getData() || resp.getData().isEmpty()) {
                                    page--;
                                }
                                mAdapter.addData(resp.getData());
                            }
                            if (null != conten_refresh) {
                                conten_refresh.finishRefresh();
                                conten_refresh.finishLoadMore();
                            }
                        }

                        @Override
                        public void onError(ApiException apiException) {
                            DialogHelper.hideDialog();
                            if (page > 1) {
                                page--;
                            }
                            if (null != conten_refresh) {
                                conten_refresh.finishRefresh();
                                conten_refresh.finishLoadMore();
                            }
                        }
                    });
        } else if (Objects.equals(GALLERY_TYPE, GALLERY_MINE)) {
            NetworkMaster.getInstance().getCommonService().galleryMineList(new ServiceCallback<BaseResp<List<GalleryBean>>>() {
                @Override
                public void onSuccess(BaseResp<List<GalleryBean>> resp) {
                    DialogHelper.hideDialog();
                    if (page == 1) {
                        mAdapter.setNewData(resp.getData());
                    } else {
                        if (null == resp.getData() || resp.getData().isEmpty()) {
                            page--;
                        }
                        mAdapter.addData(resp.getData());
                    }
                    if (null != conten_refresh) {
                        conten_refresh.finishRefresh();
                        conten_refresh.finishLoadMore();
                    }
                }

                @Override
                public void onError(ApiException apiException) {
                    DialogHelper.hideDialog();
                    if (page > 1) {
                        page--;
                    }
                    if (null != conten_refresh) {
                        conten_refresh.finishRefresh();
                        conten_refresh.finishLoadMore();
                    }
                }
            });
        } else {
            NetworkMaster.getInstance().getCommonService().galleryCollectList(category_id, keyword, sort_field, sort_order,
                    new ServiceCallback<BaseResp<List<GalleryBean>>>() {
                        @Override
                        public void onSuccess(BaseResp<List<GalleryBean>> resp) {
                            DialogHelper.hideDialog();
                            mAdapter.setNewData(resp.getData());
                            if (null != conten_refresh) {
                                conten_refresh.finishRefresh();
                                conten_refresh.finishLoadMore();
                            }
                        }

                        @Override
                        public void onError(ApiException apiException) {
                            DialogHelper.hideDialog();
                            if (null != conten_refresh) {
                                conten_refresh.finishRefresh();
                                conten_refresh.finishLoadMore();
                            }
                        }
                    });
        }
    }

    private void downloadUrl(String midId, String downLoadUrl, String fileName, int position) {
        File folder = new File(getActivity().getExternalCacheDir().getAbsoluteFile().getPath() + File.separator + "downloads");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String imageFile = fileName + ".jpg";
        File file = new File(folder, imageFile);
        if (file.exists()) {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        DownLoadApkUtils.download(downLoadUrl, file, new DownLoadApkUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.d(TAG, "onDownloadSuccess");
                ToastUtils.showCenterToast("下载成功：" + file.getAbsolutePath());
                //下载后增加使用次数
                NetworkMaster.getInstance().getCommonService().getAddUseCount(midId, new ServiceCallback() {
                    @Override
                    public void onSuccess(Object jsonObj) {
                        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_ACTIVITY_MAP_REFRESH, position));
                    }

                    @Override
                    public void onError(ApiException apiException) {
                        ToastUtils.showCenterToast(apiException.errorInfo.error);
                    }
                });
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), file.getAbsolutePath(), fileName, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
            }

            @Override
            public void onDownloading(float progress) {
                Log.d(TAG, "onDownloading  : " + progress);

            }

            @Override
            public void onDownloadFailed(String msg) {
                Log.d(TAG, "onDownloadFailed");
                ToastUtils.showCenterToast("下载失败：" + msg);
            }
        });
    }

    private void collect(GalleryBean bean, int position) {
        if ("0".equals(bean.getIs_collect())) {
            NetworkMaster.getInstance().getCommonService().gallerySysCollect(bean.getId(), new ServiceCallback() {
                @Override
                public void onSuccess(Object jsonObj) {
                    bean.setIs_collect("1");
                    mAdapter.notifyItemChanged(position);
                    ToastUtils.showCenterToast("收藏成功");
                }

                @Override
                public void onError(ApiException apiException) {
                    ToastUtils.showCenterToast(apiException.errorInfo.error);
                }
            });
        } else {
            NetworkMaster.getInstance().getCommonService().gallerySysCollectCancel(bean.getId(), new ServiceCallback() {
                @Override
                public void onSuccess(Object jsonObj) {
                    bean.setIs_collect("0");
                    mAdapter.notifyItemChanged(position);
                    ToastUtils.showCenterToast("取消收藏成功");
                }

                @Override
                public void onError(ApiException apiException) {
                    ToastUtils.showCenterToast(apiException.errorInfo.error);
                }
            });
        }
    }

    private void delMine(GalleryBean bean, int position) {
        NetworkMaster.getInstance().getCommonService().galleryMineDel(bean.getId(), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                mAdapter.notifyItemRemoved(position);
                mAdapter.getData().remove(position);
            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_FRAGMENT_UPLOAD_MAP_SUCCESS:
                if (GALLERY_TYPE.equals(GALLERY_MINE)) {
                    NetworkMaster.getInstance().getCommonService().addMap(messageEvent.getMsg(), new ServiceCallback<BaseResp>() {
                        @Override
                        public void onSuccess(BaseResp jsonObj) {
                            DialogHelper.hideDialog();
                            if (jsonObj.getCode() == 1) {
                                ToastUtils.showCenterToast("上传成功");
                                page = 1;
                                loadContent();

                            } else {
                                ToastUtils.showCenterToast(jsonObj.getMsg());
                            }
                        }

                        @Override
                        public void onError(ApiException apiException) {
                            DialogHelper.hideDialog();
                            ToastUtils.showCenterToast(apiException.errorInfo.error);
                        }

                    });
                }
                break;
            case MessageType.TYPE_ON_ACTIVITY_MAP_REFRESH:

                int position = messageEvent.getPosition();
                if (position == -1) {
                    page = 1;
                    loadContent();
                } else {
                    mAdapter.getData().get(position).setUse_count(String.valueOf(Integer.parseInt(mAdapter.getData().get(position).getUse_count()) + 1));
                    mAdapter.notifyItemChanged(position);
                }
                break;
        }
    }

    public interface OnGallerySelListener {
        void onSel(GalleryBean bean);
    }
}